
app.controller('UserListCtl',function($cookieStore ,$scope ,$compile ,InfoUserService ,InfoUserRoleService ,InfoAuthService ,InfoRoleAuthService ,InfoUserAuthService,URL ,MODE ,permissions){
		var vm = $scope.vm = {
			infoUser:{},
			editUser:{},
			roles:[],
			searchArgs:{},
			initOptions:[], //列表中空div的id
			initEvent:[], //绑定到列表中空div的事件操作
			selectRole:{},
			selectUser:{}
		};
		var authZTree;

		/*
		 * bootstrap table初始化
		 */
		$scope.init = function (searchArgs) {
			//---先销毁表格 ---
			$("#userTable").bootstrapTable('destroy');
			//---初始化表格,动态从服务器加载数据---
			$("#userTable").bootstrapTable({
				url:URL.BASEURL + URL.USERURL + "getList",
				method:'GET',
				cache:false,
				striped: true, //是否显示行间隔色
				pagination: true, //是否显示分页
				pageSize: 10, //每页的记录行数
				pageNumber: 1, //初始化加载第一页，默认第一页
				queryParams:function queryParams(params){
					//分页参数
					var param = {
						limit: params.pageSize,
						page: params.pageNumber
					};
					for(var key in searchArgs){
						param[key]=searchArgs[key]
					}
					return param;
				},
				queryParamsType:'',
				sidePagination:'server',
				responseHandler : function (res) {
					/*
					 * 加载服务器数据之前的处理程序，可以用来格式化数据。
					 * 参数：res为从服务器请求到的数据。
					 * 这里将服务器返回的数据重新做了组装。
					 */
					var result = {};
					result.rows = res.data.items;
					result.total = res.data.totalCount;
					vm.initOptions = [];//清空数组
					vm.initEvent = [];//清空数组
					vm.searchArgs = {};//清空搜索对象
					return result;
				},
				onLoadError:function (err) {
					if(err == 1001){
						Lobibox.alert("error",{
							msg:'您尚未开通该权限！'
						});
						return;
					}else if(err == 1101){
						location.href = "./"; //跳转到登录页
					}
				},
				columns: [{
								field:'',
								title:'#',
								radio:true
							},{
								field: 'id',
								title: '用户ID',
								align:'center'
							},{
								field: 'userName',
								title: '用户名',
								align:'center'
							},{
								field: 'userSex',
								title: '性别',
								align:'center'
							},{
								field: 'userEmail',
								title: '邮箱',
								align:'center'
							},{
								field: 'phoneNum',
								title: '手机号',
								align:'center'
							},{
								field: 'roleName',
								title: '角色',
								align:'center'
							},{
								field:'',
								title:'操作',
								formatter:$scope.operateFormatter,
								align:'center'
							}
				],
				onLoadSuccess: function(){
					//加载成功时执行
					//table加载完成之后
					$scope.bindOperate();
				},
				onCheck:function (row,element) {
					vm.selectUser.id = row.id;
				}
			});
		}

		/**
		 * 行为操作
		 * @param value 字段值
		 * @param row  行元素
		 * @param index 行下标
		 */
		$scope.operateFormatter = function (value,row,index) {
			//界面预留一个没有任何class的div
			var str = "<div id = 'row" + row.id +"'></div>";
			//div的id列表
			vm.initOptions.push("row" + row.id);
			//动态的html存在事件
			vm.initEvent.push("<a href='' ng-click = 'edit(" + row.id + ")'>" + "编辑" + "&nbsp&nbsp&nbsp&nbsp"
				+ "</a>" + "<a href='' ng-click = 'delete(" + row.id + ")'>" + "删除" + "</a>");
			return str

		};

		/**
		 * 绑定列表操作并编译 是ng-click生效
		 */
		$scope.bindOperate = function (){
			for(var i = 0; i < vm.initOptions.length;i++) {
				var option = vm.initOptions[i];
				var event = vm.initEvent[i];
				//将动态的html添加到记录好的空div中
				var $el = $(event).appendTo("#"+option);
				//利用$compile编译这段代码 使ng-click生效
				$compile($el)($scope);
			}
		};

		/**
		 * 列表查询
		 */
		$scope.queryList = function () {
			if(vm.infoUser.phoneNum){
				vm.searchArgs.phoneNum = vm.infoUser.phoneNum;
			}
			if(vm.infoUser.userEmail){
				vm.searchArgs.email = vm.infoUser.userEmail;
			}
			$scope.init(vm.searchArgs);
		}
		$scope.queryList();


		/**
		 * 添加用户之前初始化
		 */
		$scope.initAddUser = function () {
			$scope.addUsers = true;
			$scope.mode = MODE.add;
			$scope.$broadcast("initAdd");
		}

		/**
		 * 编辑
		 */
		$scope.edit = function(id){
			InfoUserService.get(id).then(function (data) {
				if(data.code == '1'){
					$scope.$broadcast("infoUser",data.data);
					$('#addUserModal').modal('show');
				}
			});
		};

		/**
		 * 删除
		 */
		$scope.delete = function (id) {
			Lobibox.confirm({
				msg: "确定删除该数据吗？",
				callback: function ($this, type) {
					if (type === 'yes') {
						InfoUserService.delete(id).then(function (data) {
							if(data.code == '1'){
								Lobibox.alert('success', {
									msg: "删除成功",
									callback: function ($this,type) {
										if(type == 'ok'){
											$scope.queryList();
										}
									}
								});

							}
						});
					}
				}
			});

		};

		/**
		 * 监听事件
		 */
		$scope.$on("user.queryList",function (event,data) {
			$scope.queryList();
		});


		/**
		 * ztree 设置
		 */
		/************* zTree设置  *****************/
		var setting = {
			check: {
				enable: true,
				chkboxType: { "Y" : "ps", "N" : "ps" }
			},
			data: {
				simpleData: {
					enable: true,
					idKey: "id",
					pIdKey: 'parentId'
				}
			},
			view: {
				showLine: false,
				showIcon: false
			}
		};

	/**
	 * 获取资源树图数据
	 */
	$scope.initTree = function(userId,roleId) {
		vm.treeData;
		InfoRoleAuthService.findRoleAndAuth(userId,roleId).then(function (data) {
			vm.treeData = data.data.auths;
			vm.roles = data.data.roles;

			for(var i = 0; i < vm.treeData.length; i++) {
				// 默认展开顶级节点
				if(vm.treeData[i].pId == 0) {
					vm.treeData[i].open = true;
				}
				if(vm.treeData[i].checked == 'true'){
					vm.treeData[i].chkDisabled = true;
				}
				if(vm.treeData[i].expAuth == 'true'){
					vm.treeData[i].checked = true;
				}
                vm.treeData[i].name = vm.treeData[i].authName;
			}


			$.fn.zTree.init($("#authTree"), setting, vm.treeData);
			authZTree = $.fn.zTree.getZTreeObj("authTree");
			authZTree.expandAll(true)
		});
	};

	// $scope.initTree(0,1);

	/**
	 * 选择角色后关联对应的资源
	 * @param role
	 */
	$scope.selectRole = function(role){
		vm.selectRole = $.extend(true,{},role);
		$scope.initAuthTreeByRoletId(role.id);
	};

	$scope.initRoleAndAuthForUser = function () {

		if(!vm.selectUser.id){
			Lobibox.alert("error",{
				msg:"请选择要授权的用户！",
				callback:function () {
					$('#addRoleAuthModal').modal('hide');
				}
			});
			return;
		}

		/* 重新加载树 重置 */
		vm.selectRole = {};
		InfoUserRoleService.getRoleByUserId(vm.selectUser.id).then(function (data) {
			if(data.code == 1){
				vm.selectRole.id = data.data.roleId;
				$scope.initTree(vm.selectUser.id,vm.selectRole.id);
			}else{
				$scope.initTree(0,0);
			}

		});


	};

	/**
	 *  初始化页面根据账户ID来获取资源树图数据
	 * @param roleId
	 */
	$scope.initAuthTreeByRoletId = function(roleId){
		InfoAuthService.findRoleAuthByRoleId(roleId).then(function (data) {
			var nodes = data.data;
			for(var i = 0 ; i < nodes.length; i++) {
				if(nodes[i].checked == "true") {
					nodes[i].chkDisabled = true;
					nodes[i].open = true;
				}
				// 默认展开顶级节点
				if(nodes[i].parentId == 0) {
					nodes[i].open = true;
				}
                nodes[i].name = nodes[i].authName;
			}
			$.fn.zTree.init($("#authTree"), setting, nodes);
			authZTree = $.fn.zTree.getZTreeObj("authTree");
		});
	}

	/**
	 * 保存 用户与角色对应关系、用户和资源的对应关系
	 * 注：用户与资源的对应关系中并不包含用户所对应的角色的资源
	 */
	$scope.addRoleAndAuth = function () {
		if(!vm.selectRole.id){
			Lobibox.alert("error", {
				msg:"请先为账户授权角色"
			});
		}
		if(vm.selectUser.id) {
			var model = {};
			model.userId = vm.selectUser.id;
			model.roleId = vm.selectRole.id;
			model.auths = [];
			var nodes = authZTree.getCheckedNodes(true);
			for(var i = 0 ; i < nodes.length; i++) {
				model.auths[i] = {};
				model.auths[i].authId = nodes[i].id;
				model.auths[i].userId = vm.selectUser.id;
			}
			InfoUserAuthService.addRoleAndAuth(model).then(function (data) {
				if(data.code == 1){
					Lobibox.alert("success",{
						msg:"当前用户授权成功",
						callback:function () {
							$('#addRoleAuthModal').modal('hide');
							$scope.queryList();
						}
					});

				}
			});
		}
	};

});

/**
 * 子控制器
 */
app.controller('modalAdd', ['$cookieStore','InfoUserService' , '$scope', '$http', '$state','$window','MODE', function($cookieStore,InfoUserService, $scope, $http, $state, $window, MODE) {
	$scope.infoUser = {};

	$scope.submit = function() {
		var user = $scope.infoUser;
		if($scope.mode == MODE.add) {
			if(user.userSex == "男"){
                user.userSex = 1;
			}else if(user.userSex == "女"){
                user.userSex = 2;
			}
			InfoUserService.addUser(user).then(function(data) {
				if(data.code == '1') {
					/**
					 *该服务贯穿作用域发出一个向上的事件，并通知哪些注册在rootScope.Scope上的监听器。
					 * 该事件的生命周期开始于emit被启动的地方，事件一直朝着根作用域传递，传递期间并通知哪些注册在作用域上的监听器，
					 * 如果这期间一个监听器接受到了这个事件，会注销这个事件，那么事件将会停止向上继续传播。
					 */
					$scope.$emit("user.queryList");
				} else {
					alert("插入失败");
				};
			});
		} else if($scope.mode == MODE.edit) {
			InfoUserService.updateUser(user).then(function(data) {
				if(data.code == '1') {
					$scope.setUsersList($scope.page.pageNo);
				} else {
					alert("更新失败");
				};
			});
		}

		$('#addUserModal').modal('hide');
		/**
		 * 模态框被隐藏时触发
		 */
		$('#addUserModal').on('hidden.bs.modal', function() {
			$scope.close();
		});
	};

	$scope.close = function() {

		$scope.userform.$setPristine();
		$scope.userform.$setUntouched();
		$scope.infoUser = {};
	};

	/**
	 * 模态框被隐藏时触发
	 */
	$('#addUserModal').on('hidden.bs.modal', function() {
		$scope.close();
	});

	/**
	 * 监听来自父controller的传递的消息
	 */
	$scope.$on("infoUser",function (event,data) {
		$scope.infoUser = $.extend({},true,data);
	});

	$scope.$on("initAdd",function(){
		$scope.infoUser.userSex = "男";
		$scope.infoUser.locked = 0;
	});
}]);
